package com.fileuptool.utils;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
/**
 * 
* @ClassName: FileOperateUtil 
* @Description: TODO
* @author dinghao
* @date 2018年3月15日 下午4:41:01 
*
 */
public class FileOperateUtil {
 
 
	private static FileOperateUtil fpu=new FileOperateUtil();
 
 
	public static FileOperateUtil getInstance(){
		return fpu;
	}
 
 
	/**
	 * 将文件转换成字节数组
	 * @param file 需要转换的文件
	 * @return
	 */
	public byte[] getBytes(File file){  
		byte[] buffer = null;  
          	try {     
	              FileInputStream fis = new FileInputStream(file);  
	              ByteArrayOutputStream bos = new ByteArrayOutputStream(1000);  
	              byte[] b = new byte[1000];  
	              int n;  
	              while ((n = fis.read(b)) != -1) {  
	                  bos.write(b, 0, n);  
	              }  
	              fis.close();  
	              bos.close();  
	              buffer = bos.toByteArray();  
	          } catch (FileNotFoundException e) {  
	              e.printStackTrace();  
	          } catch (IOException e) {  
	              e.printStackTrace();  
	          }  
	        return buffer;  
	 }
	 
	 /**
	  * 将字节数组写入到指定的文件夹中
	  * @param bt
	  * @param filePath
	  * @param fileName
	  * @return
	  */
	 public String writeFileToService(byte[] bt, String filePath,String fileName) {  
	        BufferedOutputStream bos = null;  
	        FileOutputStream fos = null;  
	        File file = null;  
	        try {  
	            File dir = new File(filePath);
	            //判断文件目录是否存在 
	            if(!dir.exists()){ 
	                dir.mkdirs();  
	            }  
	            file = new File(filePath+"\\"+fileName);  
	            fos = new FileOutputStream(file);  
	            bos = new BufferedOutputStream(fos);  
	           bos.write(bt);  
	       } catch (Exception e) {  
	           e.printStackTrace();  
	       } finally {  
	           if (bos != null) {  
	                try {  
	                    bos.close();  
	                } catch (IOException e1) {  
	                    e1.printStackTrace();  
	                }  
	            }  
	            if (fos != null) {  
	                try {  
	                    fos.close();  
	                } catch (IOException e1) {  
	                    e1.printStackTrace();  
	                }  
	            }  
	        }  
	        return filePath+"\\"+fileName;
	 }
}
